﻿// Copyright (c) Microsoft Corporation
//
// All rights reserved. 
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file 
// except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING 
// WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY 
// OR NON-INFRINGEMENT. 
//
// See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.

using System;
using System.Threading.Tasks;
using TED.WindowsAzure.Unplugged.Mobile.Extensions;
using TED.WindowsAzure.Unplugged.Mobile.Storage;
using TED.WindowsAzure.Unplugged.Mobile.Sync.Folder;
using TED.WindowsAzure.Unplugged.Mobile.Sync.Storage;

namespace TED.WindowsAzure.Unplugged.Mobile.Sync.Context
{
    public class SyncContext : ISyncContext
    {
        private IRemoteFileStorage _remoteFileStorage;
        private SyncEnabledStorage _syncEnabledStorage;

        public SyncContext(UnpluggedMobileServiceClient client)
        {
            Client = client;
            IsInitialized = false;
        }

        public bool IsInitialized { get; private set; }

        public UnpluggedMobileServiceClient Client { get; private set; }

        /// <summary>
        ///     Initialize the sync context using default storage rather than user defined
        /// </summary>
        /// <returns></returns>
        public Task InitializeAsync(IRemoteFileStorage remoteFileStorage)
        {
            UIDispatcher.Initialize();
            return Task.Factory.StartNew(() =>
            {
                IsInitialized = true;
                _remoteFileStorage = remoteFileStorage;

                _syncEnabledStorage = new SyncEnabledStorage(new DefaultSyncFileStorage());
            });
        }

        /// <summary>
        ///     This is the local container where all the files will be kept
        /// </summary>
        /// <param name="folderName">string</param>
        /// <returns></returns>
        public Task<ISyncFolder> GetSyncFolderAsync(string folderName)
        {
            return Task.Factory.StartNew<ISyncFolder>(() =>
            {
                EnsureInitialized();

                return new SyncFolder(folderName, _syncEnabledStorage, _remoteFileStorage);
            });
        }

        private void EnsureInitialized()
        {
            if (!IsInitialized)
            {
                throw new InvalidOperationException(
                    "The Sync Context must be initialized before IMobileServiceSyncTable instances can be created.");
            }
        }
    }
}